// pages/translate/translate.js
import {request} from "../../utils/request.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputLanuage: ['中文', '英文', '日语', '韩语','法语'],
    index1: 0,
    index2: 0,
    outputLanuage1: ['英文', '日语', '韩语','法语'],
    outputLanuage2: ['中文'],
    translatedWord:''
  },
  youdaoTranslateType: ['ZH_CN', 'EN', 'JA', 'KR','FR'],
  youdaoVoiceType:['','eng','jap','ko','fr'],
  audio:null,
  needTranslate:'',
  pickerChange: function(e) {
    this.setData({
      index1: e.detail.value
    })

  },
  pickerChange1: function(e) {

    this.setData({
      index2: e.detail.value
    })

  },
  translate:function(){
    if (this.needTranslate != ''){
      let i1 = this.data.index1;
      let i2 = i1 == 0 ? Number(this.data.index2) + 1 : this.data.index2;
      request({
        url: `http://fanyi.youdao.com/translate?&doctype=json&type=${this.youdaoTranslateType[i1]}2${this.youdaoTranslateType[i2]}&i=${this.needTranslate}`,
        method:'get'
      }).then( res => {
        this.setData({
          translatedWord: res.data.translateResult[0][0].tgt
        })
        wx.hideLoading()
      })
    }else{
      wx.showToast({
        title: 'A~还没输入要翻译的内容哟',
        icon:'none'
      })
    }
  },
  getInputWord:function(e){
    this.needTranslate = e.detail.value
    if (this.needTranslate == ''){
      this.setData({
        translatedWord:''
      })
    }
  },
  play: function () {
    if (this.audio != null) {
      this.audio.destroy()
    }
    let text = this.data.translatedWord;
    let audio = wx.createInnerAudioContext();
    this.audio = audio;
    let i1 = this.data.index1;
    let i2 = i1 == 0 ? Number(this.data.index2) + 1 : this.data.index2;
    let voiceType = this.youdaoVoiceType[i2];
    if(voiceType == ''){
      wx.showToast({
        title: '这都要读音?不会吧?不会吧?不会把?',
        icon:'none'
      })
      return
    }
    audio.src = `http://tts.youdao.com/fanyivoice?word=${text}&le=${voiceType}`;
    audio.play()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})